﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EncuentraloSilverlight.Web.Models;
using System.Data.Linq;

namespace EncuentraloSilverlight.Web.Models
{
    public class SellerRepository
    {
        private EncuentraloDataBaseModelDataContext db;

        public SellerRepository()
        {
            db = new EncuentraloDataBaseModelDataContext();
            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<Seller>(k => k.Address);
            options.LoadWith<Seller>(k => k.Products);
            db.LoadOptions = options;
        }

        //Query Methods
        public IQueryable<Seller> FindAllSellers()
        {
            return db.Sellers;
        }

        public IQueryable<Seller> FindSellerFromName( string Name)
        {
            var temp = db.Sellers.Where(k => k.Name.Equals(Name));
            return temp;

        }

        public Seller GetSeller(int id)
        {
            return db.Sellers.SingleOrDefault(d => d.SellerID == id);
        }

        //entregar todos los productos vendedores por comuna
       
        public IQueryable<Product> GetAllProductsOfSellersByCommune(string commune)
        {
            var v1 = from seller in db.Sellers
                     where seller.Address.Commune.Equals(commune)
                     select seller.Products;

            return v1 as IQueryable<Product>;
        }
        //entregar todos los vendedores vendedores por comuna

        public IQueryable<Seller> GetAllSellersByCommune(string commune)
        {
            var v1 = from seller in db.Sellers
                     where seller.Address.Commune.Equals(commune)
                     select seller;

            return v1;
        }
        // Entrega todas las comunar registradas
        public IQueryable<string> GetAllCommunesBySellers()
        {
            var v1 = from seller in db.Sellers
                     select seller.Address.Commune;
            return v1;

        }
        // Insert/Delete
        public void Add(Seller seller)
        {
            db.Sellers.InsertOnSubmit(seller);
            Save();
        }
        public void Delete(Seller seller)
        {
            db.Products.DeleteAllOnSubmit(seller.Products);
            db.Addresses.DeleteOnSubmit(seller.Address);
            db.Sellers.DeleteOnSubmit(seller);
            Save();
        }

        // Persistence
        private void Save()
        {
            db.SubmitChanges();
        }
    }
}